package com.diandiansong.app.ui.cart;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.diandiansong.app.App;
import com.diandiansong.app.R;
import com.diandiansong.app.entity.CommodityInfoInfo;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.ui.index.GoodDetail;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;
import com.diandiansong.app.widgets.AddAndMinusViewInItem;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import diandiansong.library.ui.base.FastListFragment;
import diandiansong.library.utils.BaseEntity;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.ImgLoader;

/**
 * 购物车
 */
public class CartMain extends BaseAct {

    public static void start(Context context) {
        Intent starter = new Intent(context, CartMain.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitle("购物车");
        initRithtText("编辑", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editmode
                if (mRightView1.getText().toString().equals("编辑")) {
                    mRightView1.setText("完成");
                    SubFragment.editMode();

                } else {
                    mRightView1.setText("编辑");
                    SubFragment.buyMode();
                }
            }
        });

        addFragment(new SubFragment());
    }

    public static class SubFragment extends FastListFragment {

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            EventBus.getDefault().register(this);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            EventBus.getDefault().unregister(this);
        }

        public static class Mode {
            boolean edit;

            public Mode(boolean edit) {
                this.edit = edit;
            }
        }

        public static void editMode() {
            EventBus.getDefault().post(new Mode(true));
        }

        public static void buyMode() {
            EventBus.getDefault().post(new Mode(false));
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void chmode(Mode mode) {
            mEditMode = mode.edit;
            if (mEditMode) {
                ll_content.setVisibility(View.INVISIBLE);
                goBill.setText("删除");
                goBill.setBackgroundColor(getResources().getColor(R.color.app_red));

            } else {
                ll_content.setVisibility(View.VISIBLE);
                goBill.setText("去结算");
                goBill.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            }
        }

        boolean mEditMode = false;

        /**
         * 允许子类重写，替换布局
         * <p/>
         * must have @id/swiperefreshlayout @id/listview
         *
         * @return layoutId
         */
        @Override
        protected int getLayoutId() {
            return R.layout.cart_main;
        }

        TextView mTotalPrice;
        TextView mTotalCount;
        View ll_content;
        TextView goBill;
        CheckBox cbAll;

        /**
         * viewCreated 后调用
         *
         * @param rootView framentView
         */
        @Override
        public void initView(View rootView) {
            super.initView(rootView);
            goBill = rootView.findViewById(R.id.do_add_cart);
            ll_content = rootView.findViewById(R.id.ll_content);
            mTotalPrice = rootView.findViewById(R.id.tv_total_price);
            mTotalCount = rootView.findViewById(R.id.tv_count);
            cbAll = rootView.findViewById(R.id.cb_all);
            cbAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelected.clear();
                    if (cbAll.isChecked()) {
                        mSelected.addAll(mAdapter.getData());
                    }
                    count();
                    notifyDataSetChanged();
                }
            });
            goBill.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mSelected.size() == 0) {
                        return;
                    }
                    if (mEditMode) {
                        String[] ids = new String[mSelected.size()];
                        for (int i = 0; i < mSelected.size(); i++) {
                            CommodityInfoInfo.Data data = mSelected.get(i);
                            ids[i] = data.getCart_id();
                        }
                        onLoading();
                        A.cartDel(ids, new CCallBack<BaseEntity>() {
                            @Override
                            public void onSuccess(BaseEntity baseEntity) throws Exception {
                                for (int i = 0; i < mSelected.size(); i++) {
                                    CommodityInfoInfo.Data data = mSelected.get(i);
                                    mAdapter.remove(data);
                                }
                                mSelected.clear();
                                onLoaded();
                            }

                            @Override
                            public void onFailure(int code, String msg) {
                                onLoaded();
                                toast(msg);
                            }
                        });

                    } else {
                        //购物车验证
                        OrderCheck.start(getActivity(), mSelected);
                    }
                }
            });
        }

        @Override
        public int getItemLayoutRes() {
            return R.layout.good_item_add_minus;
        }

        @Override
        public void bindItemView(final int position, @NonNull View convertView) {
            ImageView check = findViewById(convertView, R.id.iv_cb);
            check.setVisibility(View.VISIBLE);


            final CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) getItem(position);

            ImageView iv = findViewById(convertView, R.id.iv_logo);
            ImgLoader.display(iv, item.getImgs());

            if (isSelected(item)) {
                check.setImageResource(R.drawable.img19);
            } else {
                check.setImageResource(R.drawable.img18);
            }

            fastText(convertView, R.id.tv_1, item.getCommodityName());
            fastText(convertView, R.id.tv_2, item.getCommoditySubtitle());


            String unit = item.getUnit();
            if (unit == null || unit.isEmpty() || unit.equals("/")) {
                unit = "";
            } else {
                unit = "/" + unit;
            }

            fastText(convertView, R.id.tv_3, "￥" + item.getPrice() + unit);

            AddAndMinusViewInItem aamvii = findViewById(convertView, R.id.add_minus);
            aamvii.setMin(1);
            aamvii.setNum(item.getNum());
            aamvii.setOnChangeListener(new AddAndMinusViewInItem.OnChangeListener() {
                @Override
                public void onChange(int num) {
                    item.setNum(num);
                    count();
                }
            });


            fastOnClick(convertView, R.id.iv_cb, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateSelected(item);
                    notifyDataSetChanged();
                }
            });
        }

        List<CommodityInfoInfo.Data> mSelected = new ArrayList<>();

        private void updateSelected(CommodityInfoInfo.Data single) {
            boolean contain = false;
            for (int i = 0; i < mSelected.size(); ++i) {
                if (single == mSelected.get(i)) {
                    contain = true;
                    mSelected.remove(i);
                    break;
                }
            }
            if (!contain) {
                mSelected.add(single);
            }
            count();
            if (mSelected.size() == mAdapter.getDataSize()) {
                cbAll.setChecked(true);
            } else {
                cbAll.setChecked(false);
            }
        }

        private void count() {
            float money = 0f;
            int count = 0;
            for (int m = 0; m < mAdapter.getData().size(); ++m) {
                for (int i = 0; i < mSelected.size(); ++i) {
                    CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) (mAdapter.getItem(m));
                    if (item == mSelected.get(i)) {
                        money += item.getPriceF() * item.getNum();
                        count++;
                    }
                }
            }
            money = App.readable(money);
            mTotalPrice.setText("合计：￥" + money);
            mTotalCount.setText("数量：" + count + "件");
        }

        private boolean isSelected(CommodityInfoInfo.Data single) {
            for (int i = 0; i < mSelected.size(); ++i) {
                if (single == mSelected.get(i)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public void onRefresh() {
            mSelected.clear();
            count();
            super.onRefresh();
        }

        /**
         * 滑到底部时调用
         */
        @Override
        protected void loadMore() {
            A.cart(mPage, new CCallBack<CommodityInfoInfo>() {
                @Override
                public void onSuccess(CommodityInfoInfo o) throws Exception {
                    List<CommodityInfoInfo.Data> data = o.getData();
                    if (mPage.equals("0")) {
                        mAdapter.setData(data);
                    } else {
                        mAdapter.addAll(data);
                    }
                    if (mAdapter.getDataSize() > 0) {
                        mPage = ((CommodityInfoInfo.Data) getLast()).getCart_id();
                    }
                    onLoadFinishHasMore(data.size() >= Api.PAGE_SIZE);
                }

                @Override
                public void onFailure(int code, String msg) {
                    onLoadFinishNoMore();
                    toast(msg);
                }
            });
        }

        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            AddAndMinusViewInItem aamvii = view.findViewById(R.id.add_minus);
            CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) getItem(position);
            GoodDetail.start(getActivity(), item.getCommodityId());
        }
    }
}
